<?php

namespace App\Util;

class MstPayUtil
{

    private $appId;
    private $des3Key;
    private $appKey;
    private $serviceSubjectId;
    private $baseUrl = "https://api.meishitong168.cn/openapi/simple/%s/%s/cashout";
    private $platformId;
    private $callBackUrl;

    public function __construct()
    {
        $this->appId = config('mst.appId');
        $this->des3Key = config('mst.des3Key');
        $this->appKey = config('mst.appKey');
        $this->serviceSubjectId = config('mst.serviceSubjectId');
        $this->platformId = config('mst.platformId');
        $this->callBackUrl = config('mst.notifyUrl');
    }
    //https://api.meishitong168.cn/openapi/simple/{appId}/alipay/cashout
    //https://api.meishitong168.cn/openapi/simple/{appId}/alipaytobank/cashout


    /*
     * mobileNumber string手机号，只支持大陆 是
     * idcard string身份证号（大陆居民二代身份证）是
     * name  string姓名（身份证对应的真实姓名）是
     * cardNo string收款人支付宝账户 是
     * dealSerialNo string流水号，单笔提现流水的流水号，由商户生成保持唯一性，64 个英文字符以内 是
     * serviceSubjectIdstring 服务主体 ID，参考商户和美事通签订合作合同主体120001天津大杰致美信息技术有限公司140801山西美事信息技术有限责任公司 是
     * money string提现金额 (分) 是
     * platformId string三方对接平台的用户ID如果没有此字段则 workerUrl 字段必填见说明
     * workerUrl string作品链接如果没有此字段则 platformId 字段必填见说明
     * settlementBasis string结算依据 否
     * remark string打款流水单备注，会在回调（查询）提现状态的时候回传 否
     * callbackUrl string支付状态回调 URL否
     */
    public function alipayCashOut($param, $cashOutType)
    {
        $param['platformId'] = $this->platformId;
        $param['serviceSubjectId'] = $this->serviceSubjectId;
        $param['callbackUrl'] = $this->callBackUrl;
        $param['remark'] = $cashOutType;
        $data = $this->encryptParam($param);
        $mess = mt_rand(10000, 99999);
        $t = time();
        $sign = $this->sign($data, $t, $mess);
        $url = sprintf($this->baseUrl, $this->appId, $cashOutType);
        //$url="http://192.168.2.120:9501/callback/mstpay";
        $queryData = [
            'data' => $data, 'timestamp' => (string)$t, 'mess' => (string)$mess, 'sign' => $sign
        ];
        try {
            $result = ComUtil::httpReq($url, $queryData);
            $result = json_decode($result, true);
            if ($result['status'] === "SUCCESS") {
                return $result['data'] ?? ['code' => -1, 'msg' => '未知错误'];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => '未知错误'];
        }
    }

    /**
     * 加密请求参数
     * @param $param
     * @return false|string
     */
    public function encryptParam($param)
    {
        return openssl_encrypt(json_encode($param), "des3", $this->des3Key, 8, substr($this->des3Key, 0, 8));
    }

    public function sign($data, $timestamp, $mess)
    {
        $str = sprintf("data=%s&key=%s&mess=%s&timestamp=%s", $data, $this->appKey, $mess, $timestamp);

        return hash_hmac("sha256", $str, $this->appKey);
    }

}
